package com.adee.netty.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class NettyClient {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group) // 设置线程组
                    .channel(NioSocketChannel.class) // 设置客户端通道的实现类（反射）
                    .handler(new ChannelInitializer<SocketChannel>() { //

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast("encoder", new ProtobufEncoder());
                            ch.pipeline().addLast(new NettyClientHandler2()); // 加入自己的handler
                        }
                    });
            System.out.println("客户端 ok...");
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();
//            channelFuture.channel().closeFuture().sync();
            Channel channel = channelFuture.channel();
            System.out.println("已获取到channel");
            Scanner in = new Scanner(System.in);
            String line;
            while ((line = in.nextLine()) != null) {
                ByteBuf buf = channel.alloc().buffer();
                buf.writeBytes(line.getBytes(StandardCharsets.UTF_8));
                channel.writeAndFlush(buf);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully(); //
        }

    }
}
